package fr.emn.integration.synthese.controle.EleveDialog;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;

import fr.emn.integration.synthese.abstraction.Cours;
import fr.emn.integration.synthese.abstraction.Eleve;
import fr.emn.integration.synthese.presentation.EleveDialog;
import fr.emn.integration.synthese.presentation.JTableEleveModel;

public class ControlJButtonValider implements ActionListener {

	private Cours modele;
	private JTable listeModules;
	private EleveDialog parent;
	private boolean creation;

	public ControlJButtonValider(EleveDialog parent, Cours modele,
			JTable listeModules, boolean creation) {
		this.modele = modele;
		this.listeModules = listeModules;
		this.parent = parent;
		this.creation = creation;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		if (creation) {
			Eleve eleve = new Eleve(parent.getNom().getText(), parent
					.getPrenom().getText(), parent.getMail().getText(),
					(String) parent.getGenre().getSelectedItem());

			try {
				this.burnDB(eleve);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		else{
			Eleve aModifier = new Eleve(parent.getDB(),modele.getEleveCourant());
			aModifier.setNom(parent.getNom().getText());
			aModifier.setPrenom(parent.getPrenom().getText());
			aModifier.setMail(parent.getMail().getText());
			aModifier.setGenre((String)parent.getGenre().getSelectedItem());
			
			try {
				modele.purgeGroupeEleve(modele.getEleveCourant());
				this.burnDB(aModifier);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
	}
	
	public void burnDB (Eleve eleve) throws SQLException {
		modele.saveEleve(eleve, creation);

		for (int i = 0; i < listeModules.getRowCount(); i++) {
			
			if (!(listeModules.getModel().getValueAt(i, 1).toString()).equals("") ||
					((String) listeModules.getModel().getValueAt(i, 0)).equals("")){
				
					modele.saveRelation(modele.findEleveId(eleve.getNom(),eleve.getPrenom()),
							modele.findGroupeId(listeModules.getModel().getValueAt(i,1).toString(),
									modele.findModuleId(listeModules.getModel().getValueAt(i, 0).toString())));
					parent.setVisible(false);

			}
		}

		
	}

}